package com.canbot.u05.activity;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.alibaba.fastjson.JSON;
import com.canbot.u05.R;
import com.canbot.u05.activity.attendance.AttendanceInitActivity;
import com.canbot.u05.activity.customvoice.tool.GridSpacingItemDecoration;
import com.canbot.u05.activity.dance.DanceManagerActivity;
import com.canbot.u05.activity.editmodule.EditModuleActivity;
import com.canbot.u05.activity.editmodule.IFunction;
import com.canbot.u05.activity.guide.GuideActivity;
import com.canbot.u05.activity.reception.ReceptionModeSettingActivity;
import com.canbot.u05.activity.roadGuide.RoadGuideActivity;
import com.canbot.u05.activity.shoppingGuide.codeMarketing.CodeMainActivity;
import com.canbot.u05.activity.shoppingGuide.merchandiseShoppingGuide.SelectSettingTypeActivity;
import com.canbot.u05.activity.shoppingGuide.sales.SellModePropagandaActivity;
import com.canbot.u05.activity.training.TrainingListViewActivity;
import com.canbot.u05.activity.vipguide.SiteSettingActivity;
import com.canbot.u05.activity.vipguide.VipGuideActivity;
import com.canbot.u05.adapter.AppRecyclerViewAdapter;
import com.canbot.u05.api.U05RobotManger;
import com.canbot.u05.bean.AppInfo;
import com.canbot.u05.bean.JsonResponse;
import com.canbot.u05.bean.guide.LocalPointsBean;
import com.canbot.u05.socket.IpMsgConst;
import com.canbot.u05.socket.MsgSendUtils;
import com.canbot.u05.socket.MsgType;
import com.canbot.u05.utils.Logger;
import com.canbot.u05.utils.OkHttpUtils;
import com.canbot.u05.utils.PathConst;
import com.canbot.u05.utils.SPUtils;
import com.canbot.u05.utils.ToastTools;
import com.canbot.u05.widget.LoadingDialogUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;

/**
 * 手持pad 应用设置界面
 **/
public class IndustryModActivity extends BaseActivityNoTitle implements View.OnClickListener {

    private static final String TAG = "IndustryModActivity";

    private ViewPager mViewPager;

    private ImageView imageViewLeft;

    private ImageView imageViewRight;

    // 是否打开远程视频
    private boolean isOpenRemoteVideo = false;

    private ProgressDialog tipDialog;

    private int homePage;

    private List<ResolveInfo> resolveInfos = new ArrayList<>();

    private List<AppInfo> mbrowList;

    private final int constant = 8;

    private AppRecyclerViewAdapter appRecyclerViewAdapter;
    private ToastTools toastTools;
    private String[] orderModuleName;
    private IFunction[] functions;
    private Dialog dialogLoading;
    private ArrayList<LocalPointsBean> siteList;
    private String jsonDatas;

    Handler handler = new Handler();
    private List<AppInfo> appInfos;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Logger.d(TAG, "onCreate");
        setContentView(R.layout.act_industry_mod);
        toastTools = ToastTools.newInstance(this);
        mbrowList = new ArrayList<>();
        orderModuleName = getResources().getStringArray(R.array.order_edit_module_names);

        U05RobotManger.getInstance().playSound(PathConst.PAD_MODE_DIR + "yyy_01.wav");
        mViewPager = (ViewPager) findViewById(R.id.viewpager_industry);

        imageViewLeft = (ImageView) findViewById(R.id.btn_industry_left);
        imageViewLeft.setOnClickListener(this);
        imageViewLeft.setImageResource(R.drawable.icon_left_press);
        imageViewRight = (ImageView) findViewById(R.id.btn_industry_right);
        imageViewRight.setImageResource(R.drawable.icon_right_nor);
        imageViewRight.setOnClickListener(this);

        mViewPager.setAdapter(pagerAdapter);
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {
            }

            @Override
            public void onPageSelected(int i) {

                homePage = i;
                isPress(i);

            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });


    }


    private PagerAdapter pagerAdapter = new PagerAdapter() {

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {

            return arg0 == arg1;
        }

        @Override
        public int getCount() {

            return mbrowList == null ? 0 : (mbrowList.size() + 7) / constant;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            (container).removeView((View) object);
        }

        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            final LayoutInflater inflater = LayoutInflater.from(container.getContext());
            final View view = inflater.inflate(R.layout.industry_adapter, container, false);

            List<AppInfo> mbrowList1 = new ArrayList<>();
            for (int i = 0; i < getCount(); i++) {
                if (i == position) {
                    mbrowList1 = mbrowList.subList(i * constant, i * constant + constant > mbrowList.size() ? mbrowList.size() : i * constant + constant);
                }
            }
            RecyclerView recyclerView = view.findViewById(R.id.gv_content_action);
            recyclerView.setLayoutManager(new GridLayoutManager(IndustryModActivity.this, 4));  //网格布局，每行为4
            recyclerView.addItemDecoration(new GridSpacingItemDecoration(4, 30, false));
            appRecyclerViewAdapter = new AppRecyclerViewAdapter(IndustryModActivity.this, mbrowList1);
            recyclerView.setAdapter(appRecyclerViewAdapter);
            //获取点击的position
            appRecyclerViewAdapter.setOnItemClickLisener(new AppRecyclerViewAdapter.OnItemClickLisener() {
                @Override
                public void getPosition(AppInfo info) {
                    Logger.e(TAG, "点击的position = " + position);
                    handleFunction(info);
                }
            });
            container.addView(view);
            return view;
        }

        @Override
        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }
    };


    /**
     * 处理点击应用图标后的函数操作
     *
     * @param info
     */
    private void handleFunction(AppInfo info) {
        int funIndex = -1;
        String appName = info.getAppName();
        for (int i = 0; i < orderModuleName.length; i++) {
            if (appName.equals(orderModuleName[i])) {
                funIndex = i;
            }
        }

        if (funIndex != -1) {
            functions[funIndex].fun();
        }
    }


    private void getData() {
        dialogLoading = LoadingDialogUtils.createLoadingDialog(this, getString(R.string.request));
        functions = new IFunction[]{this::recommendedProducts, this::salesPromotion, this::commentator, this::mapGuide, this::vipGuide,
                this::posterDisseminate,  this::clockIn, this::officeTrainingHotel, this::playVideo,
                this::dancePerform, this::soundPlay, this::usher, this::visit};

        HashMap<String, Object> hasMap = new HashMap<>();
        hasMap.put("get_data", "get_data");

        OkHttpUtils.upLoadFile("http://" + IpMsgConst.CHEST_SOCKET_HOST + ":7755/" + "appInfo", hasMap, new OkHttpUtils.OkHttpCallBack() {
            @Override
            public void onSuccess(String result) {
                Log.e(TAG, "success ： " + result);

                final JsonResponse strMsgBean = JSON.parseObject(result, JsonResponse.class);

                if (strMsgBean.getRc() == 0) {
                    Log.e(TAG, "success ： 获取数据成功");
                    jsonDatas = strMsgBean.getResult().toString();


                    appInfos = JSON.parseArray(jsonDatas, AppInfo.class);

                    splitAppInfos(appInfos);
                    cancelDialog();


                } else {
                    toastTools.showText("获取数据失败");
                    cancelDialog();

                }


            }

            @Override
            public void onFailure() {
                toastTools.showText("服务器异常,请重试!");
                Log.e(TAG, "getData onFailure");
                cancelDialog();

            }
        });

    }


    /**
     * 分离数据
     *
     * @param appInfos
     */
    private void splitAppInfos(List<AppInfo> appInfos) {

        ArrayList<AppInfo> upDataInfos = new ArrayList<>();

        for (int i = 0; i < appInfos.size(); i++) {
            AppInfo appInfo = appInfos.get(i);
            if (appInfo.isMainFunction()) {
                upDataInfos.add(appInfo);
            }
        }

        if (upDataInfos.size() > 1) {
            Collections.sort(upDataInfos, new Comparator<AppInfo>() {
                @Override
                public int compare(AppInfo o1, AppInfo o2) {
                    return o1.getPosition() - o2.getPosition();
                }
            });
        }

        if (upDataInfos.size() == 0) {
            for (int i = 0; i < 5; i++) {
                upDataInfos.add(appInfos.get(i));
            }
        }

        //更新UI
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mbrowList.clear();
                mbrowList.addAll(upDataInfos);
                pagerAdapter.notifyDataSetChanged();
                homePage = 0;
            }
        });


    }


    public void editModule(View view) {
        Intent intent = new Intent();
        intent.putExtra("appInfo", jsonDatas);

        Log.e(TAG, "jsonDatas:" + jsonDatas);

        startotherActivity(IndustryModActivity.this, EditModuleActivity.class);
        finish();
    }

    @Override
    public void onClick(View view) {
        final int count = mViewPager.getAdapter().getCount();
        switch (view.getId()) {
            case R.id.btn_industry_left:
                if (mViewPager.getCurrentItem() == 0) {
                    return;
                } else {
                    mViewPager.setCurrentItem(mViewPager.getCurrentItem() - 1, true);
                }
                break;
            case R.id.btn_industry_right:
                if (mViewPager.getCurrentItem() == count - 1) {
                    return;
                } else {
                    mViewPager.setCurrentItem(mViewPager.getCurrentItem() + 1, true);
                }
                break;
            default:
                break;
        }
    }

    public void isPress(int homePage) {
        Logger.e(TAG, "homePage -> " + homePage);
        if (homePage == (mbrowList.size() + 7) / constant - 1) {
            imageViewLeft.setImageResource(R.drawable.icon_left_nor);
            imageViewRight.setImageResource(R.drawable.icon_right_press);
        } else if (homePage == 0) {
            imageViewLeft.setImageResource(R.drawable.icon_left_press);
            imageViewRight.setImageResource(R.drawable.icon_right_nor);
        } else {
            imageViewLeft.setImageResource(R.drawable.icon_left_nor);
            imageViewRight.setImageResource(R.drawable.icon_right_nor);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (appInfos == null || appInfos.size() == 0) {
            getData();
        }
        MsgSendUtils.sendStringMsg(MsgType.EYE_MOTION, "14");

    }

    protected void startotherActivity(Context context, Class<?> cls) {
        Intent intent = new Intent(context, cls);
        startActivity(intent);
        overridePendingTransition(R.anim.face_zoom_enter,
                R.anim.face_zoom_exit);
    }

    public void backIndustry(View view) {
        Log.d("View", " back ");
        //停止播放音频
        MsgSendUtils.sendStringMsg(MsgType.STOP_SOUND, "stop_sound");
        finish();
    }


    @Override
    protected void onPause() {
        super.onPause();
        cancelDialog();
    }

    /**
     * 产品推荐
     */
    public void recommendedProducts() {

        Intent intent = new Intent(this, SelectSettingTypeActivity.class);
        intent.putExtra("isFirst", true);
        startActivity(intent);
        overridePendingTransition(R.anim.face_zoom_enter, R.anim.face_zoom_exit);
    }

    /**
     * 促销揽客
     */
    public void salesPromotion() {
        Intent intent = new Intent(this, SellModePropagandaActivity.class);
        intent.putExtra("isFirst", true);
        startActivity(intent);
        overridePendingTransition(R.anim.face_zoom_enter,
                R.anim.face_zoom_exit);
    }

    /**
     * 导览解说
     */
    public void commentator() {
        startActivity(new Intent(this, GuideActivity.class));
        overridePendingTransition(R.anim.face_zoom_enter,
                R.anim.face_zoom_exit);
    }

    /**
     * 地点带领
     */
    public void mapGuide() {
        startActivity(new Intent(this, RoadGuideActivity.class));
        overridePendingTransition(R.anim.face_zoom_enter,
                R.anim.face_zoom_exit);
    }

    /**
     * 贵宾导引
     */
    public void vipGuide() {

        dialogLoading = LoadingDialogUtils.createLoadingDialog(this, getResources().getString(R.string.request));
        dialogLoading.show();
        final String receptionRoute = SPUtils.getString(IndustryModActivity.this, "receptionRoute", null);

        Logger.e("123", receptionRoute);

        String url = IpMsgConst.HTTP_URL_CHEST + "guideMapAction";
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("type", 8 + "");
        OkHttpUtils.upLoadFile(url, hashMap, new OkHttpUtils.OkHttpCallBack() {


            @Override
            public void onSuccess(String result) {

                if (!TextUtils.isEmpty(result)) {
                    Type gsonType = new TypeToken<ArrayList<LocalPointsBean>>() {
                    }.getType();
                    siteList = new Gson().fromJson(result, gsonType);
                    for (int i = 0; i < siteList.size(); i++) {
                        if (siteList.get(i).getPointName().equals(receptionRoute)) {
                            cancelDialog();
                            startActivity(new Intent(IndustryModActivity.this, VipGuideActivity.class)
                                    .putExtra("isdialog", "isdialog")
                                    .putExtra("receptionRoute", receptionRoute)
                            );
                            return;
                        }
                    }
                    cancelDialog();
                    startActivity(new Intent(IndustryModActivity.this, SiteSettingActivity.class)
                            .putExtra("isFirst", true));
                } else {
                    cancelDialog();
                    startActivity(new Intent(IndustryModActivity.this, VipGuideActivity.class));
                }

            }

            @Override
            public void onFailure() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        cancelDialog();
                        ToastTools.newInstance(IndustryModActivity.this).showText(getString(R.string.network_error));

                    }
                });

            }
        });


    }

    private void cancelDialog() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (dialogLoading != null) {
                    if (dialogLoading.isShowing()) {
                        dialogLoading.cancel();
                    }
                }
            }
        });
    }

    /**
     * 海报宣传
     */
    public void posterDisseminate() {
        Intent intent = new Intent(this, CodeMainActivity.class);
        startActivity(intent);
        overridePendingTransition(R.anim.face_zoom_enter, R.anim.face_zoom_exit);
    }

    /**
     * 考勤打卡
     */
    public void clockIn() {
        startActivity(new Intent(IndustryModActivity.this, AttendanceInitActivity.class));
        overridePendingTransition(R.anim.face_zoom_enter, R.anim.face_zoom_exit);
    }

    /**
     * 培训主持
     */
    public void officeTrainingHotel() {
        startActivity(new Intent(IndustryModActivity.this, TrainingListViewActivity.class));
        overridePendingTransition(R.anim.face_zoom_enter, R.anim.face_zoom_exit);
    }


    /**
     * 视频播放
     */
    public void playVideo() {
        toastTools.showText("视频播放");
    }

    /**
     * 舞蹈表演
     */
    public void dancePerform() {
        startotherActivity(this, DanceManagerActivity.class);
    }

    /**
     * 音频播放
     */
    public void soundPlay() {
        toastTools.showText("音频播放");
    }

    /**
     * 迎宾接待
     */
    public void usher() {
        MsgSendUtils.sendStringMsg(MsgType.SEND_PAD_MEETING_START, "handSetting");
        Intent intent = new Intent(this, ReceptionModeSettingActivity.class);
        startActivity(intent);
        overridePendingTransition(R.anim.face_zoom_enter, R.anim.face_zoom_exit);

    }

    /**
     * 预约拜访
     */
    public void visit() {
        toastTools.showText("预约拜访");
    }
}
